package com.tth.learn.addproperties.java;

/**
 * 例子：创建三个窗口卖票，总票数为100张
 *
 * @Author tth
 * @Date 2022/10/31 11:20
 */
public class WindowTest2 {
    public static void main(String[] args) {
        Window2 w2 = new Window2();

        Thread t1 = new Thread(w2);
        t1.setName("窗口1");
        t1.start();

        Thread t2 = new Thread(w2);
        t2.setName("窗口2");
        t2.start();

        Thread t3 = new Thread(w2);
        t3.setName("窗口3");
        t3.start();
    }
}

class Window2 implements Runnable {
    // 此处可以不使用static。因为虽然开了3个窗口，但是实际上共用的是一个Window对象
    private int ticket = 100;

    // 同步锁
    private Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (obj) {
//            synchronized (this) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ": 卖票，票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}

